package com.boarsoft.boar.demo.product.service;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.demo.order.entity.PocOrder;
import com.boarsoft.boar.demo.product.biz.PocProductBiz;
import com.boarsoft.boar.demo.product.entity.PocProduct;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.MessageService;

@Component("productTransactionSvc")
public class ProductTransactionSvc implements MessageService {
	
	@Autowired
	PocProductBiz productBiz;
	
	private static final Logger log = LoggerFactory.getLogger(ProductTransactionSvc.class);

	@SuppressWarnings("unchecked")
	@Override
	public void put(Message m) throws Exception {
		log.info("Received product transaction ==> {}", m.getContent());
		Map<String, Object> pm = (Map<String, Object>) m.getContent();
		int productId = (int ) pm.get("productId");
		int amount = (int ) pm.get("amount");
		int productNum = (int ) pm.get("productNum");
		Integer status = (Integer) pm.get("status");
//		PocOrder o = (PocOrder) m.getContent();
//		int productId = o.getProductId();
//		int amount = o.getAmount();
//		int productNum = o.getProductNum();
//		short status = o.getStatus();
		
		PocProduct product = productBiz.get(productId);
		if (product != null) {
			// check金额
			if (amount != product.getProductPrice() * productNum) {
				log.error("订单金额异常...");
				return;
			}
			int num =0;
			if (PocOrder.STATUS_FINISH == status) {
				num = product.getStoreNum() - productNum;
				log.debug("正常下单num：" + num );
				if (num < 0) {
					log.error("产品库存不足...");
					return;
				}
			} else if (PocOrder.STATUS_CANCEL == status){
				num = product.getStoreNum() + productNum;
				log.debug("下单冲正num：" + num );
			} else {
				log.error("订单状态异常...");
				return;
			}
			product.setStoreNum(num);
		} else {
			log.error("未找到产品...");
			return;
		}
		productBiz.update(product);
	}
}